package com.example.excise06.service.impl;

import com.baidu.aip.face.AipFace;
import com.example.excise06.service.AiFaceService;
import com.example.excise06.service.dto.FaceItem;
import lombok.Data;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Data
@Service
@ConfigurationProperties(prefix = "baidu.ai")
public class AiFaceServiceImpl implements AiFaceService {
    @Value("${baidu.ai.appid}")
    private String appId;
    @Value("${baidu.ai.apikey}")
    private String apiKey;
    @Value("${baidu.ai.secret}")
    private String secret;
    @Value("${baidu.ai.groupid}")
    private String groupId;

    @Override
    public List<FaceItem> detectImageBase64(String imageBase64, String maxNum) {
        //1、构造人脸检测必须的参数
        HashMap<String, String> options = new HashMap<String,String>();
        //指定人脸检测时需要返回的字段：年龄，颜值，表情，脸型，性别，眼镜佩戴情况
        options.put("face_field", "age,beauty,expression,faceshape,gender,glasses");
        //指定一张照片中最多识别的人脸数量，10张人脸
        options.put("max_face_num", "10");
        //指定人脸类型为生活照类型
        options.put("face_type", "LIVE");
        //指定图片输入方式为base64编码后的图片
        String image = imageBase64;
        String imageType = "BASE64";
        //开始调用人脸检测
        AipFace client = getClient();
        JSONObject res = client.detect(image, imageType, options);
        System.out.println("detectImage result>>"+res.toString(2));
        //获得人脸检测结果，解析JSON结果，组装成为List<FaceItem>列表
        if (res.has("error_code") && res.getInt("error_code") == 0) {
            JSONObject result = res.getJSONObject("result");
            //如果返回结果中人脸数>0表示检测到人脸
            if (result.has("face_num") && result.getInt("face_num") > 0) {
                JSONArray faceList = result.getJSONArray("face_list");
                List<FaceItem> faceItems = new ArrayList<>();
                for (int i = 0; i < faceList.length(); i++) {
                    //新建人脸检测对象
                    FaceItem faceItem = new FaceItem();
                    //获取队列中人脸
                    JSONObject faceJson = faceList.getJSONObject(i);
                    faceItem.setAge(faceJson.getDouble("age"));
                    faceItem.setBeauty(faceJson.getInt("beauty"));
                    JSONObject expression = faceJson.getJSONObject("expression");
                    faceItem.setExpression(expression.getString("type"));
                    JSONObject gender = faceJson.getJSONObject("gender");
                    faceItem.setGender(gender.getString("type"));
                    JSONObject glasses = faceJson.getJSONObject("glasses");
                    faceItem.setGlasses(glasses.getString("type"));
                    JSONObject faceShape = faceJson.getJSONObject("face_shape");
                    faceItem.setFaceShape(faceShape.getString("type"));
                    faceItem.setFaceToken(faceJson.getString("face_token"));
                    faceItems.add(faceItem);
                }
                return faceItems;
            }
        }
        return null;
    }

    @Override
    public String searchFace(String faceToken) {
        //传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String,String>();
        options.put("quality_control", "NORMAL");
        String image = faceToken;
        String imageType = "FACE_TOKEN";
        String groupIds = groupId;
        //开始调用人脸搜索
        AipFace client = getClient();
        JSONObject res = client.search(image, imageType, groupIds, options);
        System.out.println(res.toString(2));
        if (res.has("error_code") && res.getLong("error_code") == 0) {
            JSONObject resResult = res.getJSONObject("result");
            //解析人脸搜索结果
            JSONArray userList = resResult.getJSONArray("user_list");
            if (userList != null && userList.length() > 0) {
                JSONObject userJson = userList.getJSONObject(0);
                //得到人脸识别结果
                String userId=userJson.getString("user_id");
                return userId;
            }
        }
        return null;
    }

    public AipFace getClient() {
        return new AipFace(appId, apiKey, secret);
    }
}